package com.ecloud.common.web.jackson;

import java.io.IOException;

import com.ecloud.common.base.translate.AutoTranslate;
import com.ecloud.common.web.translate.CustomSerializeFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * 字段翻译处理
 *
 * @author LiuGangQiang Create in 2021/08/19
 */
public class TranslateFieldSerializer extends JsonSerializer<Object> {
    /**
     * 自定义序列化工厂
     *
     * @author LiuGangQiang Create in 2021/08/19
     */
    private CustomSerializeFactory factory;
    /**
     * 自动翻译注解
     *
     * @author LiuGangQiang Create in 2021/08/19
     */
    private AutoTranslate translate;

    /**
     * 构造器
     *
     * @author LiuGangQiang Create in 2021/08/19
     * @param factory   序列化工厂
     * @param translate 翻译注解
     */
    public TranslateFieldSerializer(CustomSerializeFactory factory, AutoTranslate translate) {
        this.translate = translate;
        this.factory = factory;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        /* 只处理字符串类型 */
        if (value instanceof String) {
            /* 根据注解的来源决定处理方式 */
            gen.writeString(this.factory.build(translate.source()).serialize(translate.type(), value.toString()));
        } else {
            gen.writeObject(value);
        }
    }
}
